# -*- coding: utf-8 -*-
"""
"""

from datetime import datetime

from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode

from abserver.model import DeclarativeBase, metadata, DBSession, BuildBlessing


class Task(DeclarativeBase):
    """This Entity represent a build task, which really means a component Variety that
    has been built within the build of a component.
    """
    # table options
    __tablename__ = 'task'

    # columns
    task_id = Column(Integer, primary_key=True, autoincrement=True)
    variety = Column(Unicode(64), nullable=False)
    build_status = Column(Integer, nullable=False) # from the BS_* enumeration below
    task_start_time = Column(DateTime, nullable=False)
    task_alive_time = Column(DateTime, nullable=False)
    task_end_time = Column(DateTime, nullable=True)
    build_live = Column(Boolean, nullable=False)
    build_comment = Column(Unicode(), nullable=True)
    build_id = Column(Integer, ForeignKey('build.build_id'))
    blessing_id = Column(Integer, ForeignKey('buildblessing.blessing_level'))

    # relationships
    ## blobs
    build = relation('Build', backref='tasks')
    blessing = relation('BuildBlessing', backref='tasks')

    BS_BUILDING, BS_BUILD_SUCCESS, BS_TESTING, BS_TEST_SUCCESS, BS_BUILD_FAILED, BS_TEST_FAILED = range(6)

    BUILD_STATUS = [
        (BS_BUILDING, "Building"),
        (BS_BUILD_SUCCESS, "Build Success"),
        (BS_TESTING, "Testing"),
        (BS_TEST_SUCCESS, "Test Success"),
        (BS_BUILD_FAILED, "Build failed"),
        (BS_TEST_FAILED, "Test failed"),
        ]

    # This dictionary describes the severity of the task status. A good sunnary of all the tasks of
    # a build is the maximum of these values
    STATUS_SEVERITY = { BS_BUILD_SUCCESS: 0,
                        BS_TEST_SUCCESS: 1,
                        BS_BUILDING: 2,
                        BS_TESTING: 3,
                        BS_TEST_FAILED: 4,
                        BS_BUILD_FAILED: 5,
                        }

    def __init__(self, build, branch, variety_name):
        self.build = build
        self.variety = variety_name
        self.build_status = 0 # 'BUILDING'
        now = datetime.now()
        self.task_start_time = now
        self.task_alive_time = now
        self.build_live = True
        self.blessing = BuildBlessing.get_unblessed()
        DBSession.add(self)

    @classmethod
    def get(cls, task_id):
        return DBSession.query(cls).filter(cls.task_id == task_id).one()

    def blessing_name(self):
        if not self.blessing:
            return '(None)'
        return self.blessing.blessing_name
    
    def task_still_alive(self):
        self.task_alive_time = datetime.now()

    def build_blob(self):
        for b in self.blobs:
            if b.blob_type == Blob.TASK_BUILD_OUTPUT:
                return b
        return None
      
    def log_blob(self):
        for b in self.blobs:
            if b.blob_type == Blob.TASK_LOG:
                return b
        return None
